from django.contrib import admin
from .models import ToolCategory, Tool, ToolReview, ToolTag

@admin.register(ToolCategory)
class ToolCategoryAdmin(admin.ModelAdmin):
    """工具分类管理"""
    list_display = ['name', 'slug', 'icon', 'created_at']
    list_filter = ['created_at']
    search_fields = ['name', 'description']
    prepopulated_fields = {'slug': ('name',)}
    ordering = ['name']

@admin.register(ToolTag)
class ToolTagAdmin(admin.ModelAdmin):
    """工具标签管理"""
    list_display = ['name', 'slug', 'created_at']
    list_filter = ['created_at']
    search_fields = ['name']
    prepopulated_fields = {'slug': ('name',)}
    ordering = ['name']

@admin.register(Tool)
class ToolAdmin(admin.ModelAdmin):
    """工具管理"""
    list_display = ['name', 'category', 'tool_type', 'is_featured', 'is_free', 'status', 'views', 'clicks', 'rating', 'created_at']
    list_filter = ['tool_type', 'is_featured', 'is_free', 'status', 'category', 'created_at', 'updated_at']
    search_fields = ['name', 'description', 'url']
    prepopulated_fields = {'slug': ('name',)}
    filter_horizontal = []
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    readonly_fields = ['views', 'clicks', 'rating']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'slug', 'category', 'author')
        }),
        ('内容', {
            'fields': ('description', 'url', 'icon', 'screenshot')
        }),
        ('设置', {
            'fields': ('tool_type', 'is_featured', 'is_free', 'status')
        }),
        ('统计信息', {
            'fields': ('views', 'clicks', 'rating'),
            'classes': ('collapse',)
        })
    )
    
    def save_model(self, request, obj, form, change):
        """保存时自动设置作者"""
        if not change:
            obj.author = request.user
        super().save_model(request, obj, form, change)

@admin.register(ToolReview)
class ToolReviewAdmin(admin.ModelAdmin):
    """工具评价管理"""
    list_display = ['tool', 'user', 'rating', 'is_approved', 'created_at']
    list_filter = ['rating', 'is_approved', 'created_at']
    search_fields = ['comment', 'user__username', 'tool__name']
    actions = ['approve_reviews', 'disapprove_reviews']
    ordering = ['-created_at']
    
    def approve_reviews(self, request, queryset):
        """批量审核通过评价"""
        queryset.update(is_approved=True)
        self.message_user(request, f'已审核通过 {queryset.count()} 条评价')
    approve_reviews.short_description = '审核通过选中的评价'
    
    def disapprove_reviews(self, request, queryset):
        """批量拒绝评价"""
        queryset.update(is_approved=False)
        self.message_user(request, f'已拒绝 {queryset.count()} 条评价')
    disapprove_reviews.short_description = '拒绝选中的评价'
